<template>
  <div class="Date">
    <div class="time">
      <span class="number">{{ `${d || 0}` }}</span>
      <span>天</span>
    </div>
    <div class="time">
      <span class="number">{{ `${h || 0}` }}</span>
      <span>小时</span>
    </div>
    <div class="time">
      <span class="number">{{ `${m || 0}` }}</span>
      <span>分钟</span>
    </div>
    <div class="time">
      <span class="number">{{ `${s || 0}` }}</span>
      <span>秒</span>
    </div>
  </div>
</template>
<script>
export default {
  props: {
    stopTime: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      d: "",
      h: "",
      m: "",
      s: "",
      timer: null,
    };
  },
  watch: {
    stopTime(newVal) {
      if (newVal) {
        this.countTime();
      }
    },
  },
  mounted() {
    clearTimeout(this.timer);
    this.countTime();
  },
  beforeDestroy() {
    clearTimeout(this.timer);
  },
  methods: {
    countTime: function () {
      // 获取当前时间
      let date = new Date();
      let now = date.getTime();
      // 设置截止时间
      let endDate = new Date(this.stopTime);
      let end = endDate.getTime();

      // 时间差
      let leftTime = end - now;
      // 定义变量 d,h,m,s 保存倒计时的时间
      if (leftTime >= 0) {
        this.d = Math.floor(leftTime / 1000 / 60 / 60 / 24);
        this.h = Math.floor((leftTime / 1000 / 60 / 60) % 24);
        this.m = Math.floor((leftTime / 1000 / 60) % 60);
        this.s = Math.floor((leftTime / 1000) % 60);

        // 对天、时、分、秒进行格式化，不足两位前面补 0
        this.d = this.d.toString().padStart(2, "0");
        this.h = this.h.toString().padStart(2, "0");
        this.m = this.m.toString().padStart(2, "0");
        this.s = this.s.toString().padStart(2, "0");

        // 递归每秒调用 countTime 方法，显示动态时间效果
        this.timer = setTimeout(this.countTime, 1000);
      }
    },
  },
};
</script>

<style scoped>
.Date {
  width: 100%;
}
.time {
  display: flex;
  background-color: #ccc;
  text-align: center;
  color: #fff;
  margin: 5px;
  padding: 10px;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.number {
  font-size: 4rem;
}
</style>
